package middelware

import (
	"context"
	"gitee.com/qian/guser/define"
	"gitee.com/qian/guser/model"
	"gitee.com/qian/guser/shared"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/guid"
	"time"
)

var Session = sessionService{}

type sessionService struct {
}

const (
	// 用户信息存放在Session中的Key
	sessionKeyUser = "SessionKeyUser"
	hashKey        = "__HASH__"
)

func (s *sessionService) SetUser(ctx context.Context, user *model.Guser) error {
	//生成key
	key := s.GenToken(user.Id)
	err := shared.Context.Get(ctx).Cache.Set(key, user, 24*time.Hour)
	if err == nil {
		//设置到上下文
		shared.Context.SetData(ctx, g.Map{
			"token": key,
		})
	}
	return err
}

func (s *sessionService) GetUser(ctx context.Context) *model.Guser {
	shareCtx := shared.Context.Get(ctx)
	if shareCtx != nil {
		var (
			data *define.GUserMiddlewareTokenReq
		)
		if err := shareCtx.Request.Parse(&data); err != nil {
			return nil
		}
		v, err := shared.Context.Get(ctx).Cache.Get(data.Token)
		if err != nil {
			return nil
		}
		var user *model.Guser
		_ = gconv.Struct(v, &user)
		return user
	}
	return nil
}

func (s *sessionService) RemoveUser(ctx context.Context) error {
	shareCtx := shared.Context.Get(ctx)
	if shareCtx != nil {
		var (
			data *define.GUserMiddlewareTokenReq
		)
		if err := shareCtx.Request.Parse(&data); err != nil {
			return nil
		}
		_, err := shared.Context.Get(ctx).Cache.Remove(data.Token)
		if err != nil {
			return err
		}
	}
	return nil
}

//生成token
func (s *sessionService) GenToken(id int) string {
	key := guid.S()
	key, _ = gmd5.EncryptString(key + hashKey)
	key = gconv.String(id) + key
	return key
}
